package com.zk.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zk.yygh.hosp.exception.HospitalException;
import com.zk.yygh.hosp.repository.DepartmentRepository;
import com.zk.yygh.hosp.repository.HospitalRepository;
import com.zk.yygh.hosp.repository.ScheduleRepository;
import com.zk.yygh.hosp.result.ResultCodeEnum;
import com.zk.yygh.hosp.service.ScheduleService;
import com.zk.yygh.model.hosp.BookingRule;
import com.zk.yygh.model.hosp.Department;
import com.zk.yygh.model.hosp.Hospital;
import com.zk.yygh.model.hosp.Schedule;
import com.zk.yygh.vo.hosp.BookingScheduleRuleVo;
import com.zk.yygh.vo.hosp.DepartmentVo;
import com.zk.yygh.vo.hosp.ScheduleOrderVo;
import com.zk.yygh.vo.hosp.ScheduleQueryVo;
import org.joda.time.DateTime;
import org.joda.time.DateTimeConstants;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: 张凯
 * @date: 2022/6/6 - 10:50
 */
@Service
public class ScheduleServiceImpl implements ScheduleService {
    @Autowired
    private ScheduleRepository scheduleRepository;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private HospitalRepository hospitalRepository;

    @Autowired
    private DepartmentRepository departmentRepository;

    //上传排班信息
    @Override
    public void save(Map<String, Object> parameterMap) {
        //将参数转为科室信息对象
        Schedule schedule = JSONObject.parseObject(JSONObject.toJSONString(parameterMap), Schedule.class);
        //查询mongodb中是否存在对象
        Schedule scheduleFind = scheduleRepository.getScheduleByHoscodeAndHosScheduleId(schedule.getHoscode(), schedule.getHosScheduleId());
        if (scheduleFind != null) {
            //排班不为空则修改
            schedule.setCreateTime(scheduleFind.getCreateTime());
            schedule.setStatus(scheduleFind.getStatus());
        } else {
            schedule.setCreateTime(new Date());
            schedule.setStatus(1);
        }
        schedule.setUpdateTime(new Date());
        schedule.setIsDeleted(0);
        scheduleRepository.save(schedule);
    }

    //查询排班信息
    @Override
    public Page<Schedule> selectPage(int page, int limit, ScheduleQueryVo scheduleQueryVo) {
        //1.创建pageable对象: 起始页为0
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");//通过时间降序
        Pageable pageable = PageRequest.of(page - 1, limit, sort);
        //2.创建example实例
        Schedule schedule = new Schedule(); //2.1 创建查询的对象
        BeanUtils.copyProperties(scheduleQueryVo, schedule);
        ExampleMatcher matcher = ExampleMatcher.matching()    //2.2 创建匹配器
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改变默认字符串匹配方式：模糊查询
                .withIgnoreCase(true);//忽略大小写
        Example<Schedule> example = Example.of(schedule, matcher);
        //3.进行分页查询
        Page<Schedule> pages = scheduleRepository.findAll(example, pageable);
        return pages;
    }

    //删除排班信息
    @Override
    public void remove(Map<String, Object> parameterMap) {
        //将参数转为排班对象
        Schedule schedule = JSONObject.parseObject(JSONObject.toJSONString(parameterMap), Schedule.class);
        //执行删除操作
        if (schedule != null) {
            scheduleRepository.deleteById(schedule.getHosScheduleId());
        }
    }

    //查看指定医院指定科室的排班信息
    @Override
    public Map<String, Object> getScheduleRole(String hoscode, String depcode, Integer page, Integer limit) {
        //一、科室预约规则
        //1.1 封装查询条件
        Criteria criteria = Criteria.where("hoscode").is(hoscode).and("depcode").is(depcode);
        //1.2 聚合操作
        Aggregation aggregation = Aggregation.newAggregation(
                //1.2.1 匹配条件
                Aggregation.match(criteria),
                //1.2.2 分组操作
                Aggregation.group("workDate").first("workDate").as("workDate")
                        //1.2.2.1 统计数量
                        .count().as("docCount")
                        //1.2.2.2 统计总预约数量
                        .sum("reservedNumber").as("reservedNumber")
                        //1.2.2.3 统计可预约数量
                        .sum("availableNumber").as("availableNumber"),
                //1.2.3 进行排序
                Aggregation.sort(Sort.Direction.ASC, "workDate"),
                //1.2.4 分页查询
                Aggregation.skip((page - 1) * limit),
                Aggregation.limit(limit)
        );
        //1.2.5 进行聚合操作
        AggregationResults<BookingScheduleRuleVo> aggregate = mongoTemplate.aggregate(aggregation, Schedule.class, BookingScheduleRuleVo.class);//聚合操作，查询对象，返回对象
        List<BookingScheduleRuleVo> scheduleRuleResults = aggregate.getMappedResults();
        //二、分组查询的总记录数
        Aggregation totalAggregation = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("workDate")
        );
        AggregationResults<BookingScheduleRuleVo> aggregateTotal = mongoTemplate.aggregate(totalAggregation, Schedule.class, BookingScheduleRuleVo.class);
        int total = aggregateTotal.getMappedResults().size();
        //三、星期转换
        scheduleRuleResults.stream().forEach(item -> {
            item.setDayOfWeek(this.getDayOfWeek(new DateTime(item.getWorkDate())));
        });
        //四、获取医院名字
        Hospital hospital = hospitalRepository.getHospitalByHoscode(hoscode);
        String hospitalName = "";
        if (hospital != null) {
            hospitalName = hospital.getHosname();
        }
        Map<String, String> hospName = new HashMap<>();
        hospName.put("hospName", hospitalName);
        //五、封装数据并返回
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("scheduleRuleResults", scheduleRuleResults);
        resultMap.put("total", total);
        resultMap.put("baseMap", hospName);
        return resultMap;
    }

    //根据医院编号科室编号日期查询具体排班信息
    @Override
    public List<Schedule> getDetailSchedule(String hoscode, String depcode, String workDate) {
//        System.out.println(hoscode + ":" + depcode + ":" + workDate);
        //查询具体排班信息
        List<Schedule> scheduleList = scheduleRepository.findScheduleByHoscodeAndDepcodeAndWorkDate(hoscode, depcode, new DateTime(workDate).toDate());
        //填充信息
        scheduleList.stream().forEach(item -> {
            this.fillInfo(item);
        });
        return scheduleList;
    }

    /**
     * 获取排班预约周期数据
     * 医院->科室->日期->排班
     *
     * @param page
     * @param limit
     * @param hoscode
     * @param depcode
     * @return
     */
    @Override
    public Map<String, Object> getBookingScheduleRule(Integer page, Integer limit, String hoscode, String depcode) {
        //获取医院
        Hospital hospital = hospitalRepository.getHospitalByHoscode(hoscode);
        if(null == hospital) {
            throw new HospitalException(ResultCodeEnum.DATA_ERROR);
        }
        //获取医院的预约规则
        BookingRule bookingRule = hospital.getBookingRule();
        //一、根据预约规则的预约日期进行分页
        IPage iPage = bookingRuleDatePage(page, limit, bookingRule);
        //获取当亲页的日期
        List<Date> dateList = iPage.getRecords();
        System.out.println(dateList);
        //二、对当前页日期进行聚合操作->获取可预约排班规则
        Criteria criteria = Criteria.where("hoscode").is(hoscode).and("depcode").is(depcode)
                .and("workDate").in(dateList);  //封装查询条件
        Aggregation agg = Aggregation.newAggregation( //聚合操作
                //匹配条件
                Aggregation.match(criteria),
                Aggregation.group("workDate").first("workDate").as("workDate") //分组字段
                        .count().as("docCount") //计数
                        .sum("availableNumber").as("availableNumber")   //求和科室剩余预约数
                        .sum("reservedNumber").as("reservedNumber")     //求和科室可预约数
        );
        AggregationResults<BookingScheduleRuleVo> aggregateResults = mongoTemplate.aggregate(agg, Schedule.class, BookingScheduleRuleVo.class);//聚合执行
        List<BookingScheduleRuleVo> scheduleRuleVoList = aggregateResults.getMappedResults();  //获取排班预约规则
        //合并数据：日期<->预约规则
        Map<Date, BookingScheduleRuleVo> scheduleRuleVoMap = new HashMap<>();
        System.out.println("聚合结果--->"+scheduleRuleVoList);
        //对获取的排班预约规则进行时间聚合，合并数据
        if (scheduleRuleVoList != null) {
            scheduleRuleVoMap = scheduleRuleVoList.stream().collect(Collectors
                    .toMap(BookingScheduleRuleVo::getWorkDate, BookingScheduleRuleVo -> BookingScheduleRuleVo));
        }
        //三、遍历当前页的时间，获取每个预约时间对应的排班预约时间并对其进行封装
        List<BookingScheduleRuleVo> bookingScheduleRuleList = new ArrayList<>();
        for (int i = 0; i < dateList.size(); i++) {
            Date date = dateList.get(i);
            BookingScheduleRuleVo bookingScheduleRuleVo = scheduleRuleVoMap.get(date);
            if (bookingScheduleRuleVo == null) {   //说明当天没有可排班的规则
                bookingScheduleRuleVo = new BookingScheduleRuleVo();
                //设置就诊医生人数
                bookingScheduleRuleVo.setDocCount(0);
                //设置剩余预约数，-1表示无号
                bookingScheduleRuleVo.setAvailableNumber(-1);
            }
            //设置可预约日期
            bookingScheduleRuleVo.setWorkDate(date);
            bookingScheduleRuleVo.setWorkDateMd(date);
            //设置当前预约日期为周几
            bookingScheduleRuleVo.setDayOfWeek(getDayOfWeek(new DateTime(date)));
            //设置预约状态
            //最后一页最后一条记录为即将预约   状态 0：正常 1：即将放号 -1：当天已停止挂号
            if (i == dateList.size() - 1 && page == iPage.getPages()) {
                bookingScheduleRuleVo.setStatus(1);
            } else {
                bookingScheduleRuleVo.setStatus(0);
            }
            //当天预约如果过了停号时间， 不能预约
            if (i == 0 && page == 1) {
                DateTime stopTime = this.getDateTime(new Date(), bookingRule.getStopTime());
                if (stopTime.isBeforeNow()) {
                    //停止预约
                    bookingScheduleRuleVo.setStatus(-1);
                }
            }
            bookingScheduleRuleList.add(bookingScheduleRuleVo);
        }

        //四、封装可预约日期规则数据
        Map<String, Object> result = new HashMap<>();
        result.put("bookingScheduleList", bookingScheduleRuleList);
        result.put("total", iPage.getTotal());
        //其他基础数据
        Map<String, String> baseMap = new HashMap<>();
        //医院名称
        baseMap.put("hosname", hospitalRepository.getHospitalByHoscode(hoscode).getHosname());
        //科室
        Department department = departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode, depcode);
        //大科室名称
        baseMap.put("bigname", department.getBigname());
        //科室名称
        baseMap.put("depname", department.getDepname());
        //月
        baseMap.put("workDateString", new DateTime().toString("yyyy年MM月"));
        //放号时间
        baseMap.put("releaseTime", bookingRule.getReleaseTime());
        //停号时间
        baseMap.put("stopTime", bookingRule.getStopTime());
        result.put("baseMap", baseMap);
        return result;
    }

    //通过排班id获取排班信息
    @Override
    public Schedule getScheduleById(String id) {
        Schedule schedule = scheduleRepository.findById(id).get();
        fillInfo(schedule);
        return schedule;
    }

    //通过排班id获取排班订单信息
    @Override
    public ScheduleOrderVo getScheduleOrderVo(String scheduleId) {
        //创建排班订单信息
        ScheduleOrderVo scheduleOrderVo=new ScheduleOrderVo();
        //获取排班信息
        Schedule schedule = scheduleRepository.findById(scheduleId).get();
        if(null == schedule) {
            throw new HospitalException(ResultCodeEnum.PARAM_ERROR);
        }
        //获取预约规则
        Hospital hospital = hospitalRepository.getHospitalByHoscode(schedule.getHoscode());
        if(null == schedule) {
            throw new HospitalException(ResultCodeEnum.PARAM_ERROR);
        }
        BookingRule bookingRule = hospital.getBookingRule();
        if(null == schedule) {
            throw new HospitalException(ResultCodeEnum.PARAM_ERROR);
        }
        scheduleOrderVo.setHoscode(schedule.getHoscode());
        //改动
        scheduleOrderVo.setHosname(hospital.getHosname());
        scheduleOrderVo.setDepcode(schedule.getDepcode());
        //改动
        scheduleOrderVo.setDepname(departmentRepository.getDepartmentByHoscodeAndDepcode(schedule.getHoscode(), schedule.getDepcode()).getDepname());
        scheduleOrderVo.setHosScheduleId(schedule.getHosScheduleId());
        scheduleOrderVo.setAvailableNumber(schedule.getAvailableNumber());
        scheduleOrderVo.setTitle(schedule.getTitle());
        scheduleOrderVo.setReserveDate(schedule.getWorkDate());
        scheduleOrderVo.setReserveTime(schedule.getWorkTime());
        scheduleOrderVo.setAmount(schedule.getAmount());

        //退号截止天数（如：就诊前一天为-1，当天为0）
        int quitDay = bookingRule.getQuitDay();
        DateTime quitTime = this.getDateTime(new DateTime(schedule.getWorkDate()).plusDays(quitDay).toDate(), bookingRule.getQuitTime());
        scheduleOrderVo.setQuitTime(quitTime.toDate());

        //预约开始时间
        DateTime startTime = this.getDateTime(new Date(), bookingRule.getReleaseTime());
        scheduleOrderVo.setStartTime(startTime.toDate());

        //预约截止时间
        DateTime endTime = this.getDateTime(new DateTime().plusDays(bookingRule.getCycle()).toDate(), bookingRule.getStopTime());
        scheduleOrderVo.setEndTime(endTime.toDate());

        //当天停止挂号时间
        DateTime stopTime = this.getDateTime(new Date(), bookingRule.getStopTime());
        scheduleOrderVo.setStartTime(startTime.toDate());
        return scheduleOrderVo;
    }

    //生成订单后更新排班信息
    @Override
    public void update(Schedule schedule) {
        //设置更改的时间
        schedule.setUpdateTime(new Date());
        //执行更新
        scheduleRepository.save(schedule);
    }

    //对预约周期的时间进行分页
    private IPage bookingRuleDatePage(Integer page, Integer limit, BookingRule bookingRule) {
        //获取预约时间
        String releaseTime = bookingRule.getReleaseTime();
        //获取当天预约时间
        DateTime currentReleaseTime = getDateTime(new Date(), releaseTime);
        //获取预约周期
        Integer cycle = bookingRule.getCycle();
        //判断当前预约时间来变化预约周期
        if (currentReleaseTime.isBeforeNow()) {
            cycle += 1;   //当天的时间不可预约了，预约周期加1
        }
        //所有的可预约日期
        ArrayList<Date> dateList = new ArrayList<>();
        for (int i = 0; i < cycle; i++) {
            //计算当前预约日期
            DateTime currDate = new DateTime().plusDays(i); //加i天
            //设置格式
            String dateString = currDate.toString("yyyy-MM-dd");
            //转换为Date进行添加
            dateList.add(new DateTime(dateString).toDate());
        }
        //根据预约周期与limit比较进行分页
        int start = (page - 1) * limit;
        int end = (page - 1) * limit + limit;
        if (end > dateList.size()) {
            end = dateList.size();
        }
        //获取填充的数据
        ArrayList<Date> datePage = new ArrayList<>();
        //页面最多显示7条数据，多了要分页，少了就显示(从当前页的start开始)
        for (int i = start; i < end; i++) {
            datePage.add(dateList.get(i));
        }
        //进行分页，最多显示7条，多了就分页
        IPage<Date> iPage = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(page, 7, dateList.size());
        iPage.setRecords(datePage); //手动填充数据
        return iPage;

    }

    //给排班填充数据
    private void fillInfo(Schedule schedule) {
        //获取医院名字
        Hospital hospital = hospitalRepository.getHospitalByHoscode(schedule.getHoscode());
        String hospitalName = null;
        if (hospital != null) {
            hospitalName = hospital.getHosname();
        }
        //获取科室名字
        Department department = departmentRepository.getDepartmentByHoscodeAndDepcode(schedule.getHoscode(), schedule.getDepcode());
        String departmentName = null;
        if (department != null) {
            departmentName = department.getDepname();
        }
        //获取星期几
        String dayOfWeek = this.getDayOfWeek(new DateTime(schedule.getWorkDate()));
        //给排班信息填充信息
        schedule.getParam().put("hosname", hospitalName);
        schedule.getParam().put("depname", departmentName);
        schedule.getParam().put("dayOfWeek", dayOfWeek);
    }

    /**
     * 将Date日期（yyyy-MM-dd HH:mm）转换为DateTime
     */
    private DateTime getDateTime(Date date, String timeString) {
        String dateTimeString = new DateTime(date).toString("yyyy-MM-dd") + " " + timeString;
        DateTime dateTime = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm").parseDateTime(dateTimeString);
        return dateTime;
    }

    //获取星期几
    private String getDayOfWeek(DateTime dateTime) {
        String dayOfWeek = "";
        switch (dateTime.getDayOfWeek()) {
            case DateTimeConstants.SUNDAY:
                dayOfWeek = "周日";
                break;
            case DateTimeConstants.MONDAY:
                dayOfWeek = "周一";
                break;
            case DateTimeConstants.TUESDAY:
                dayOfWeek = "周二";
                break;
            case DateTimeConstants.WEDNESDAY:
                dayOfWeek = "周三";
                break;
            case DateTimeConstants.THURSDAY:
                dayOfWeek = "周四";
                break;
            case DateTimeConstants.FRIDAY:
                dayOfWeek = "周五";
                break;
            case DateTimeConstants.SATURDAY:
                dayOfWeek = "周六";
            default:
                break;
        }
        return dayOfWeek;
    }

}
